from machine import UART
from typing import Optional, Union
import time

def uart_send(uart: UART, data: Union[str, bytes]) -> Optional[int]:
    """
    Send data via UART
    """
    try:
        if isinstance(data, str):
            data = data.encode('utf-8')
        return uart.write(data)
    except Exception as e:
        print(f"UART send error: {e}")
        return None

def uart_receive(uart: UART, timeout: int = 1000) -> Optional[bytes]:
    """
    Receive data from UART
    """
    try:
        start_time = time.ticks_ms()
        while time.ticks_diff(time.ticks_ms(), start_time) < timeout:
            if uart.any():
                return uart.read()
            time.sleep_ms(10)
        return None
    except Exception as e:
        print(f"UART receive error: {e}")
        return None

def uart_send_receive(uart: UART, data: Union[str, bytes], timeout: int = 1000) -> Optional[bytes]:
    """
    Send data and wait for response
    """
    if uart_send(uart, data):
        return uart_receive(uart, timeout)
    return None
